package cn.lili.controller.wallet;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.FinanceAdminVO;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.order.aftersale.entity.vo.AfterSaleVO;
import cn.lili.modules.order.aftersale.service.AfterSaleService;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.wallet.entity.vo.WalletFrozenDetailVO;
import cn.lili.modules.wallet.service.WalletFrozenDetailService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * create by yudan on 2022/9/8
 */
@RestController
@Api(tags = "管理端,冻结钱包明细接口")
@RequestMapping("/manager/frozen/wallet/detail")
public class WalletFrozenDetailManagerController {

	@Autowired
	private PartnerService partnerService;

	@Autowired
	private RegionService regionService;
	@Autowired
	private WalletFrozenDetailService walletFrozenDetailService;

	@Autowired
	private AfterSaleService afterSaleService;

	@ApiOperation(value = "冻结钱包分佣明细")
	@RequestMapping(value = "/GetWalletFrozenDetail")
	public ResultMessage<IPage<WalletFrozenDetailVO>> GetWalletFrozenDetail(FinanceAdminVO financeAdminVO,
			PageVO page) {
		QueryWrapper queryWrapper = new QueryWrapper();

		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				financeAdminVO.setAdcode(partner.getRegionId());
			}
		}
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getMobile()), "a.mobile", financeAdminVO.getMobile());
		String regionId = financeAdminVO.getRegionId();
		if (StringUtils.isNotEmpty(regionId)) {
			List list = regionService.getItemAdCod(regionId);
			queryWrapper.in(list.size() > 0, "location", list);
		}
		// 根据code查询合伙人管理的区域Code
		if (StringUtils.isNotEmpty(financeAdminVO.getAdcode())) {
			List list = regionService.getPartnerAdCode(financeAdminVO.getAdcode(), "4");
			queryWrapper.in(list.size() > 0, "location", list);
		}
		if (financeAdminVO.getSearchTime() != null) {
			financeAdminVO.setStartTime(financeAdminVO.getSearchTime());
			// 获取下个月一号
			Calendar c = Calendar.getInstance();
			// 过去一月
			c.setTime(financeAdminVO.getSearchTime());
			c.add(Calendar.MONTH, 1);
			financeAdminVO.setEndTime(c.getTime());
			queryWrapper.between("a.createTime", financeAdminVO.getStartTime(), financeAdminVO.getEndTime());
		}
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getMobile()), "a.mobile", financeAdminVO.getMobile());
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getOrderStatus()), "a.order_status",
				financeAdminVO.getOrderStatus());
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getStoreName()), "a.storeName",
				financeAdminVO.getStoreName());
		queryWrapper.orderByDesc("a.createTime");
		queryWrapper.groupBy("a.sn");
		IPage<WalletFrozenDetailVO> data = walletFrozenDetailService.getWalletFrozenDetail(queryWrapper, page);
		if (CollectionUtils.isNotEmpty(data.getRecords())) {
			for (WalletFrozenDetailVO WalletFrozenDetail : data.getRecords()) {
				if (StringUtils.isNotEmpty(WalletFrozenDetail.getLocation())) {
					WalletFrozenDetail.setLocationName(
							regionService.getItemAdCodOrName(StringUtils.toString(WalletFrozenDetail.getLocation())));
				}
			}
		}
		return ResultUtil.data(data);
	}

	@ApiOperation(value = "冻结钱包分佣明细汇总")
	@RequestMapping(value = "/GetWalletFrozenDetailAll")
	public ResultMessage<WalletFrozenDetailVO> GetWalletFrozenDetailAll(FinanceAdminVO financeAdminVO, PageVO page) {
		QueryWrapper queryWrapper = new QueryWrapper();
		page.setPageSize(999999999);
		page.setPageNumber(1);
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				financeAdminVO.setAdcode(partner.getRegionId());
			}
		}
		String regionId = financeAdminVO.getRegionId();
		if (StringUtils.isNotEmpty(regionId)) {
			List list = regionService.getItemAdCod(regionId);
			queryWrapper.in(list.size() > 0, "location", list);
		}
		// 根据code查询合伙人管理的区域Code
		if (StringUtils.isNotEmpty(financeAdminVO.getAdcode())) {
			List list = regionService.getPartnerAdCode(financeAdminVO.getAdcode(), "4");
			queryWrapper.in(list.size() > 0, "location", list);
		}
		if (financeAdminVO.getSearchTime() != null) {
			financeAdminVO.setStartTime(financeAdminVO.getSearchTime());
			// 获取下个月一号
			Calendar c = Calendar.getInstance();
			// 过去一月
			c.setTime(financeAdminVO.getSearchTime());
			c.add(Calendar.MONTH, 1);
			financeAdminVO.setEndTime(c.getTime());
			queryWrapper.between("a.createTime", financeAdminVO.getStartTime(), financeAdminVO.getEndTime());
		}
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getMobile()), "a.mobile", financeAdminVO.getMobile());
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getOrderStatus()), "a.order_status",
				financeAdminVO.getOrderStatus());
		queryWrapper.eq(StringUtils.isNotEmpty(financeAdminVO.getStoreName()), "a.storeName",
				financeAdminVO.getStoreName());
		queryWrapper.orderByDesc("a.createTime");
		queryWrapper.groupBy("a.sn");
		IPage<WalletFrozenDetailVO> data = walletFrozenDetailService.getWalletFrozenDetail(queryWrapper, page);
		List<WalletFrozenDetailVO> list = data.getRecords();
		WalletFrozenDetailVO detail = new WalletFrozenDetailVO();
		detail.setCommission(0);
		detail.setFlowPrice(0);
		detail.setTsMoney(0);
		detail.setQyMoney(0);
		detail.setSyMoney(0);
		detail.setAdminMoney(0);
		for (WalletFrozenDetailVO s : list) {
			detail.setTsMoney(CurrencyUtil.add(s.getTsMoney(), detail.getTsMoney()));
			detail.setQyMoney(CurrencyUtil.add(s.getQyMoney(), detail.getQyMoney()));
			detail.setSyMoney(CurrencyUtil.add(s.getSyMoney(), detail.getSyMoney()));
			detail.setAdminMoney(CurrencyUtil.add(s.getAdminMoney(), detail.getAdminMoney()));
			detail.setCommission(CurrencyUtil.add(s.getCommission(), detail.getCommission()));
			detail.setFlowPrice(CurrencyUtil.add(s.getFlowPrice(), detail.getFlowPrice()));
		}
		return ResultUtil.data(detail);
	}

	@ApiOperation(value = "冻结钱包退款明细")
	@RequestMapping(value = "/refundDetailList")
	public ResultMessage<Map<String, Object>> refundDetailList(String sn) {
		Map<String, Object> map = new HashMap<>();

		List<AfterSaleVO> afterSaleList = afterSaleService.getAfterSaleVOList(sn);
		if (CollectionUtils.isNotEmpty(afterSaleList)) {
			if (null == afterSaleList.get(0).getRefundTime()) {
				return ResultUtil.error(ResultCode.AFTER_SALE_NOT_EXIST);
			}
			Map<String, Object> afterSale = new HashMap<>();
			afterSale.put("sn", afterSaleList.get(0).getSn());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 定义新的日期格式
			// format():将给定的 Date 格式化为日期/时间字符串。即：date--->String
			afterSale.put("refundTime", formatter.format(afterSaleList.get(0).getRefundTime()));
			Double actualRefundPrice = 0D;
			Double commissionPrice = 0D;
			for (AfterSaleVO afterSaleVO : afterSaleList) {
				actualRefundPrice = CurrencyUtil.add(actualRefundPrice,
						afterSaleVO.getActualRefundPrice() != null ? afterSaleVO.getActualRefundPrice() : 0D);
				commissionPrice = CurrencyUtil.add(commissionPrice,
						afterSaleVO.getCommissionPrice() != null ? afterSaleVO.getCommissionPrice() : 0D);
			}
			afterSale.put("actualRefundPrice", actualRefundPrice);
			afterSale.put("commissionPrice", commissionPrice);
			map.put("订单", afterSale);
		} else {
			return ResultUtil.error(ResultCode.AFTER_SALE_NOT_EXIST);
		}
		List<WalletFrozenDetailVO> walletFrozenDetailVOList = walletFrozenDetailService.refundDetailList(sn);
		if (CollectionUtils.isNotEmpty(walletFrozenDetailVOList)) {
			for (WalletFrozenDetailVO walletFrozenDetailVO : walletFrozenDetailVOList) {
				map.put(walletFrozenDetailVO.getName(), walletFrozenDetailVO);
			}
		}
		return ResultUtil.data(map);
	}

}
